package com.liy.jagou.auth.controller;




import com.liy.cjs.commmons.domain.LoginRequest;
import com.liy.cjs.commmons.domain.LoginResponse;
import com.liy.cjs.commmons.domain.RefreshRequest;
import com.liy.cjs.commmons.enums.ResponseCodeEnum;
import com.liy.cjs.commmons.enums.ResponseResult;
import com.liy.cjs.commmons.utils.JWTUtil;
import org.apache.commons.lang3.StringUtils;

import org.apache.tomcat.util.security.MD5Encoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

//import org.springframework.data.redis.core.HashOperations;
//import org.springframework.data.redis.core.StringRedisTemplate;


import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 */
@RestController
public class LoginController {

    /**
     * Apollo 或 Nacos
     */
    @Value("${secretKey:123456}")
    private String secretKey;

    //@Autowired
    //private StringRedisTemplate stringRedisTemplate;

    // prefix
    private static final String TOKEN_PREFIX = "ACCESS_TOKEN_";



    /**
     * 登录
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody LoginRequest request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(ResponseCodeEnum.PARAMETER_ILLEGAL.getCode(), ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
        }

        String username = request.getUsername();
        String password = request.getPassword();


        //  假设查询到用户ID是1001  "liy".equals(username) && "admin".equals(password)

        if ( StringUtils.isNotBlank(username) &&  StringUtils.isNotBlank(password) ) {

            //  生成Token
            String token = JWTUtil.generateToken(username, secretKey);

            //  生成刷新Token
            String refreshToken = UUID.randomUUID().toString().replace("-", "");

            //  放入缓存
            //HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();

            //            hashOperations.put(refreshToken, "token", token);
            //            hashOperations.put(refreshToken, "user", username);
            //            stringRedisTemplate.expire(refreshToken, JWTUtil.TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);

            /**
             * 如果可以允许用户退出后token如果在有效期内仍然可以使用的话，那么就不需要存Redis
             * 因为，token要跟用户做关联的话，就必须得每次都带一个用户标识，
             * 那么校验token实际上就变成了校验token和用户标识的关联关系是否正确，且token是否有效
             */

            // String key = MD5Encoder.encode(username.getBytes());   // 加密

            //String key = TOKEN_PREFIX + username;
            //hashOperations.put(key, "token", token);
            //hashOperations.put(key, "refreshToken", refreshToken);

             //设置过期时间
            //stringRedisTemplate.expire(key, JWTUtil.TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);


            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setToken(token);
            loginResponse.setRefreshToken(refreshToken);
            loginResponse.setUsername(username);

            return ResponseResult.success(loginResponse);
        }

        return ResponseResult.error(ResponseCodeEnum.LOGIN_ERROR.getCode(), ResponseCodeEnum.LOGIN_ERROR.getMessage());
    }

    /**
     * 退出
     */
    @GetMapping("/logout")
    public ResponseResult logout(@RequestParam("username") String username) {
        //HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
        //String key = TOKEN_PREFIX + username;
        //hashOperations.delete(key);
        return ResponseResult.success();
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refreshToken")
    public ResponseResult refreshToken(@RequestBody @Validated RefreshRequest request) {

//        String userName = request.getUserName();
//        String refreshToken = request.getRefreshToken();  // 请求携带的 refreshToken
//
//        //HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
//
//        String key = TOKEN_PREFIX + userName;
//
//
//        // 原始refreshToken
//        //String originalRefreshToken = hashOperations.get(key, "refreshToken");
//
//
//        // 1.原始refreshToken redis是否存在,存在即代表当前user登录成功的    2.请求携带的refreshToken  和 原始refreshToken 不相同
//        if (StringUtils.isBlank(originalRefreshToken) || !originalRefreshToken.equals(refreshToken)) {
//
//
//            return ResponseResult.error(ResponseCodeEnum.REFRESH_TOKEN_INVALID.getCode(), ResponseCodeEnum.REFRESH_TOKEN_INVALID.getMessage());
//        }
//
//        //  生成新token
//        String newToken = JWTUtil.generateToken(userName, secretKey);
//        hashOperations.put(key, "token", newToken);
//        stringRedisTemplate.expire(userName, JWTUtil.TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);


        return ResponseResult.success();
    }
}